package com.example.demo.service.Impl;

import com.example.demo.common.utills.CommonResult;
import com.example.demo.common.utills.PasswordEncryptUtils;
import com.example.demo.common.utills.TokenUtil;
import com.example.demo.entity.Token;
import com.example.demo.entity.User;
import com.example.demo.mapper.LoginMapper;
import com.example.demo.service.LoginService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;


@Service
public class LoginServiceImpl implements LoginService {
    @Resource
    LoginMapper loginMapper;

    @Resource
    RedisTemplate redisTemplate;

    @Override
    public CommonResult login(String account,String psd) {
        System.out.println(account+"---"+psd);
        String newPsd= PasswordEncryptUtils.MyPasswordEncryptUtil(account,psd);
        System.out.println(newPsd);
        List<User> user = loginMapper.selectUP(account);
        if(user.isEmpty()){
            return new CommonResult(401,"账户不存在");
        }
        for (User user2:user){
            if("0".equals(user2.getType())){
                return new CommonResult(405,"账户未启用");
            }
        }
        List<User> user1 = loginMapper.selectUP(newPsd);
        System.out.println(user1+"---------");
        if(user1.isEmpty()){
            return new CommonResult(402,"密码错误");
        }
        int uid=0;
        for(User user3:user1){
            uid=user3.getUid();
        }
        String sign = TokenUtil.sign(account, newPsd);
        Token token=new Token();
        token.setToken(sign);
        token.setUid(uid);
        redisTemplate.opsForValue().set(String.valueOf(uid),sign);
        System.out.println(redisTemplate.opsForValue().get(String.valueOf(uid)));
        return new CommonResult(200,"登陆成功",token);
    }
}
